<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="fade-obj" style="width:300px;height:300px;background:#000"></div>
    <button id="fade-btn">淡出</button>
    <script>
        var degree = 1;
        var obj = document.getElementById('fade-obj');
        var btn = document.getElementById('fade-btn');
        btn.addEventListener('click', function() {
            if (btn.innerHTML === '淡出') {
                changeOpacity('minus');
            } else {
                changeOpacity('add');
            }
        })

        function changeOpacity(type) {
            if (type === 'minus') {
                var opacity = 1;
                setTimeout(
                    function fn() {
                        if (opacity > 0) {
                            setTimeout(fn, 16);
                        } else {
                            btn.innerHTML = '淡入';
                            btn.removeAttribute('disabled');
                            return false;
                        }
                        opacity -= 0.01;
                        obj.style.opacity = opacity;
                        btn.setAttribute('disabled', 'disabled');
                    }, 16);
            } else {
                var opacity = 0;
                setTimeout(
                    function fn() {
                        if (opacity < 1) {
                            setTimeout(fn, 16);
                        } else {
                            btn.innerHTML = '淡出';
                            btn.removeAttribute('disabled');
                            return false;
                        }
                        opacity += 0.01;
                        obj.style.opacity = opacity;
                        btn.setAttribute('disabled', 'disabled');
                    }, 16);
            }
        }
    </script>
</body>

</html>